package com.service.devimonitor;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.bpms.common.JdbcWorker;
import com.bpms.common.VO;
import com.bpms.common.VOList;
import com.bpms.esb.IService;
import com.service.util.DateUtil;
import com.zk.atm.forms.AtmpDeviceStatusForm;
import com.zk.atm.utils.ConstantsAtmp;
import com.zk.atm.utils.ConstantsAtmpSql;
import com.zk.atm.utils.ExcelExportUtil;
import com.zk.atm.utils.InitDeviceStatusConfig;
import com.zk.atm.utils.StringUtil;

public class Atmpcmdjbserviceimpl implements IService {
    protected static Logger logger=Logger.getLogger(Atmpcmdjbserviceimpl.class);
    
    public static void main(String[] args) {
    	Atmpcmdjbserviceimpl cmdjb=new Atmpcmdjbserviceimpl();
    	VO vo=new VO();
    	//vo.setAttr(ConstantsAtmp.ATMP_CMD_METHOD_KEY_NAME, ConstantsAtmp.ATMP_DEVICE_STATUS_SHOW_TRADE_TOTAL);
    	//cmdjb.exec(vo);
    	try {
//			vo=cmdjb.show_trade_total(vo);
//			System.out.println(vo);
    		vo.setAttr(ConstantsAtmp.ATMP_CMD_METHOD_KEY_NAME, ConstantsAtmp.ATMP_DEVICE_TRADE_EXPORT);
    		 vo = cmdjb.exec(vo);
    		ExcelExportUtil excel = new ExcelExportUtil();
    		HSSFWorkbook book = null;
    		try {
    			book = excel.getExcelBook(vo);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    
	@Override
	public VO exec(VO arg0) {
		VO result_vo=new VO();
		try {
			String cmd=StringUtil.getPropertyValue(arg0.getAttr(ConstantsAtmp.ATMP_CMD_METHOD_KEY_NAME));
		    //显示交易轧帐
			if(cmd.equals(ConstantsAtmp.ATMP_DEVICE_STATUS_SHOW_TRADE_TOTAL)){
				result_vo=	this.show_trade_total(arg0);
				//System.out.println(JsonUtil.getJsonObjectByBpmVo(result_vo));
				return result_vo;
		    }else if(cmd.equals(ConstantsAtmp.ATMP_DEVICE_TRADE_EXPORT)){
		    	result_vo=this.trade_export(arg0);
		    	return result_vo;
		    }
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result_vo;
	}
	/**
	 * @author zengqun
	 * @remark 导出设备交易记录
	 * @date 2012-11-15
	 * @version 1.0
	 */
    Map<String,String> export_trade_column_map=new TreeMap<String,String>();
	protected VO trade_export(VO vo) throws Exception{
		String file_url=vo.getAttr("file_url");
		//获取要导出的设备交易记录
		VO result_vo=this.show_trade_total(vo);
		//获取表头,只加载1次
		if(export_trade_column_map.size()==0){
			Map argsMap=new HashMap<String,String>();
			argsMap.put("file_path","export_trade.properties");
			export_trade_column_map=InitDeviceStatusConfig.getConfigProperties(argsMap);
		}
		result_vo.setObj("header_map", export_trade_column_map);
		result_vo.setAttr("file_url", file_url);
		//获取生成的excel
		HSSFWorkbook hb=ExcelExportUtil.getExcelBook(result_vo);
		result_vo.setObj("hb", hb);
		return result_vo;
	}

	protected VO show_trade_total(VO args_vo) throws Exception{
		VO result_vo=new VO();
		//获取数据库的中的开始,截止时间:时分秒的时间配置
		VO sql_vo=new VO();
		String sql="select bp.val as time_value from bpm_paramvalue bp where bp.k='show_trade_total_start'";
		sql_vo.setAttr("sql", sql);
		String time_start=this.getTimeStartEndTime(sql_vo);
		if(time_start.equals("")){
			time_start="00:00:00";
		}
		sql="select bp.val as time_value from bpm_paramvalue bp where bp.k='show_trade_total_end'";
		sql_vo.setAttr("sql", sql);
		String time_end=this.getTimeStartEndTime(sql_vo);
        if(time_end.equals("")){
        	time_end="23:59:59";
        }
        //获取当前的日期:年月日
        String current_date_y_m_d=DateUtil.getInstance().getDateFormat(new Date(), "yyyy-MM-dd");
        
        //设备编码,机构编码
        String device_code=StringUtil.getPropertyValue(args_vo.getAttr("device_code"));
        String org_code=StringUtil.getPropertyValue(args_vo.getAttr("org_code"));
        //用于显示当前设备IP,名称,所属机构的信息
        String device_ip=StringUtil.getPropertyValue(args_vo.getAttr("device_ip"));
        String device_name=StringUtil.getPropertyValue(args_vo.getAttr("device_name"));
        String org_name=StringUtil.getPropertyValue(args_vo.getAttr("org_name"));
        //这个是从设备状态界面传递过来的参数
        String deviceno=StringUtil.getPropertyValue(args_vo.getAttr("deviceno"));
        //增加开始,截止日期的功能.即根据日期区间段执行查询 2012-11-19
        String date_start=StringUtil.getPropertyValue(args_vo.getAttr("date_start"));//开始日期
        //如果日期为空,则
        date_start=date_start.equals("")?current_date_y_m_d:date_start;
        String date_end=StringUtil.getPropertyValue(args_vo.getAttr("date_end"));//截止日期
        //如果日期为空,则
        date_end=date_end.equals("")?current_date_y_m_d:date_end;
        
        String createtime=StringUtil.getPropertyValue(args_vo.getAttr("createtime"));
        String isCleanMachine=StringUtil.getPropertyValue(args_vo.getAttr("isCleanMachine"));//是否轧帐
        String results=StringUtil.getPropertyValue(args_vo.getAttr("results"));//操作结果
        String status=StringUtil.getPropertyValue(args_vo.getAttr("status"));//审批状态码
        String usage=StringUtil.getPropertyValue(args_vo.getAttr("usage"));//用途
        String userid=StringUtil.getPropertyValue(args_vo.getAttr("userid"));//登录用户id
      
        if(logger.isDebugEnabled()){
           System.out.println("**********************current_date_y_m_d="+current_date_y_m_d);
        }
        sql=" select cd.* " +
//        		" cd.deviceno,cd.netnum," +
//        		" cd.payeeaccno,cd.payeename,cd.payeebank," +
//        		" cd.draweeaccno,cd.draweename,cd.draweebank, " +
//        		" cd.amount,cd.createdate " +
        		" from cm_djb cd where 1=1 "   ;
        		//" and cd.createdate='"+current_date_y_m_d+"' " +
        		if(createtime.equals("")){//如果未传递开始,截止时分秒,则默认为0点至24点
        			sql+=" and cd.createtime >='"+time_start+"' "   +
            		     " and cd.createtime <= '"+time_end+"'" ;
        		}
		if(!userid.equals("")){
			AtmpDeviceStatusForm form=new AtmpDeviceStatusForm();
			form.setUserid(userid);
			String belong_codes=ConstantsAtmpSql.getBelongOrgCodes(form);
			if(!belong_codes.equals("")){
			   sql+=" and cd.netnum in ("+belong_codes+")";
			}
			//device_sql+=ConstantsAtmpSql.ATMP_PERM_SQL.replaceAll("#userid#", userid);
		}
		//如果未输入设备号,而是默认从监控状态列表界面传递过来的device_code,则表明为初始化时候的查询,用它来执行条件限定
        if(deviceno.equals("")&&!device_code.equals("")){
    		sql+=" and cd.deviceno like '%"+device_code+"%' ";
        }
        if(!org_code.equals("")){
        	sql+=" and cd.netnum like '%"+org_code+"%' ";
        }if(!deviceno.equals("")){//如果在列表界面,执行了查询;则输入框不为空,会执行这个查询
        	sql+=" and cd.deviceno like'%"+deviceno+"%' ";
        }if(!date_start.equals("")){//开始日期
        	sql+=" and cd.createdate >='"+date_start+"'";
        }if(!date_end.equals("")){//截止日期
        	sql+=" and cd.createdate <='"+date_end+"'";
        }if(!createtime.equals("")){
        	sql+=" and cd.createtime='"+createtime+"'";
        }if(!isCleanMachine.equals("")&&!isCleanMachine.equals("-1")){
        	sql+=" and cd.isCleanMachine='"+isCleanMachine+"'";
        }if(!results.equals("")&&!results.equals("-1")){
        	sql+=" and cd.results='"+results+"'";
        }if(!status.equals("")&&!status.equals("-1")){
        	sql+=" and cd.status='"+status+"'";
        }if(!usage.equals("")){
        	sql+=" and cd.usage like '%"+usage+"%'";
        }
        System.out.println("***************************sql="+sql);
        JdbcWorker j=null;
        try {
        	j=new JdbcWorker();
        	VOList volist=j.readAll(new VO(), sql);
        	String msg="当前设备:";
        	String total=(volist==null?"0":volist.listData.size()+"");
        	if(!device_ip.equals("")){
        		msg+="IP为:"+device_ip+",";
        	}
        	if(!device_name.equals("")){
        		msg+="设备名称为:"+device_name+",";
        	}
        	if(!org_name.equals("")){
        		msg+="归属于:"+org_name+",";
        	}
        	if(!date_start.equals("")){
        		msg+="从"+date_start+"日,";
        	}
        	if(!date_end.equals("")){
        		msg+="至"+date_end+"日,";
        	}
        	if(date_start.equals("")&&date_end.equals("")){
            	msg+="在"+DateUtil.getInstance().getDateFormat(new Date(), "yyyy-MM-dd");
        	}
        	msg+=":共计交易了"+total+"笔记录!";
        	//volist=this.getStatusVOList(volist);
        	result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_RET, "0");
        	result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, msg);
        	result_vo.setObj(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_VOLIST, volist);
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			if(j!=null){
				j=null;
			}
		}
		return result_vo;
	}
	
	private VOList getStatusVOList(VOList volist) {
		VOList list=new VOList();
		Iterator it=volist.listData.iterator();
		return volist;
	}

	/**
	 * @author zengqun
	 * @remark 获取数据库的配置的开始,截止时间
	 * @param args_vo
	 * @date 2012-11-17
	 * @version 1.0
	 * @return
	 * @throws Exception
	 */
	protected String getTimeStartEndTime(VO args_vo) throws Exception{
		String time_value="";
		String sql=StringUtil.getPropertyValue(args_vo.getAttr("sql"));
		if(sql.equals("")){
			return time_value;
		}
		JdbcWorker j=null;
		try {
			j=new JdbcWorker();
			VOList volist=j.readAll(new VO(), sql);
			if(volist!=null&&volist.listData.size()>0){
				VO result_vo=(VO) volist.listData.get(0);
				time_value=StringUtil.getPropertyValue(result_vo.getAttr("time_value"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(j!=null){
				j=new JdbcWorker();
			}
		}
		return time_value;
	}
}
